﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using MyBlog.Common;
using MyBlog.Model;

namespace MyBlog
{
    public class BaseController : Controller
    {
        protected override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = Json(new JsonData
                {
                    State = AjaxState.Fail,
                    Message
                        = "出错啦.<a style='color:darkgreen; font-weight:bold;' href='javascript:;' onclick=\"layerAlert('"
                        + HttpUtility.HtmlEncode(filterContext.Exception.Message.Trim().Replace("\n", "").Replace("\r", "").Replace("'", "")
                        + (filterContext.Exception.InnerException == null ? "" : "；"
                        + filterContext.Exception.InnerException.Message.Trim().Replace("\n", "").Replace("\r", "").Replace("'", "")))
                        + "')\">点此</a>查看错误信息."
                });
            }
            else
            {
                filterContext.Result = View("~/Views/Shared/Error.cshtml", filterContext.Exception);
            }

            var dbex = filterContext.Exception as System.Data.Entity.Validation.DbEntityValidationException;
            var exMsg = string.Empty;
            if (dbex != null)
            {
                exMsg = string.Join("@", dbex.EntityValidationErrors.Select(x => string.Join(",", x.ValidationErrors.Select(y => y.ErrorMessage))));
            }
            LogHelper.WriteLog(filterContext.Exception.Message + (dbex != null ? "DBExecption：" + exMsg : "")
                + (filterContext.Exception.InnerException?.Message ?? ""));
            //标志异常已处理
            filterContext.ExceptionHandled = true;
            //base.OnException(filterContext);
        }

        /// <summary>
        /// 获取当前访问的博客用户id
        /// </summary>
        public string CurBlogUserID
        {
            get
            {
                if (RouteData.Values.ContainsKey("username") && RouteData.Values["username"] != null)
                {
                    return RouteData.Values["username"].ToString().Trim();
                }
                return "";
            }
        }

        /// <summary>
        /// 获取当前博客用户的昵称
        /// </summary>
        public string CurBlogUserName
        {
            get
            {

                if (RouteData.Values.ContainsKey("username") && RouteData.Values["username"] != null)
                {
                    return WebCache.GetNickName(RouteData.Values["username"].ToString().Trim());
                }
                return "无名";
            }
        }

        /// <summary>
        /// 获取是否有编辑的权限
        /// </summary>
        /// <returns></returns>
        public bool CanEdit
        {
            get
            {
                if (RouteData.Values.ContainsKey("username") && RouteData.Values["username"] != null && UserSession.LoginUserInfo != null)
                {
                    string username = RouteData.Values["username"].ToString().Trim();
                    if (UserSession.LoginUserInfo.Account.Same(username))
                    {
                        return true;
                    }
                }
                return false;
            }
        }

        /// <summary>
        /// 异步添加用户动态
        /// </summary>
        /// <param name="notice"></param>
        public void AddNotice(string uid, NoticeEnum type, string link, string content)
        {
            new TaskFactory().StartNew(() =>
            {
                try
                {
                    var notice = new NoticeModel
                    {
                        NoticeUID = uid,
                        NoticeEnum = type,
                        NoticeLink = link,
                        NoticeContent = content.HtmlDecode().StripHTML().SubStr(150),
                        NoticeTime = DateTime.Now
                    };
                    XiaoBoKe.NoticeService.Add(notice);
                    WebCache.Refresh(false, uid);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("添加用户动态出错：" + ex.Message);
                }
            });
        }

    }


}
